package com.example.app1.global;

import com.example.app1.enums.ResultEnum;
import com.example.app1.exception.BusinessException;
import com.example.app1.pojo.RestResp;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice(basePackages = "com.example.app1.web")
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public RestResp<String> handleException(BusinessException e) {
        return RestResp.fail(ResultEnum.FAIL.getCode(), e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public RestResp<Void> handleException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();

        StringBuilder errorMsg = new StringBuilder("参数校验异常：");
        bindingResult.getFieldErrors().forEach(fieldError -> {
            errorMsg.append(fieldError.getDefaultMessage());
            errorMsg.append(";");
        });
        return RestResp.fail(ResultEnum.FAIL.getCode(), errorMsg.toString());
    }
}
